Open
Conversation
virrius
reviewed
Mar 30, 2026
Comment on lines
+179
to
+181
| @property | ||
| def langfuse_enabled(self) -> bool: | ||
| return self.langfuse.enabled |
Comment on lines
+84
to
+107
| if getattr(config, "langfuse_enabled", False): | ||
| try: | ||
| lf_cfg = config.langfuse | ||
| if lf_cfg.public_key or lf_cfg.secret_key or lf_cfg.host: | ||
| LangfuseClient = getattr(import_module("langfuse"), "Langfuse") | ||
| kwargs = {} | ||
| if lf_cfg.public_key: | ||
| kwargs["public_key"] = lf_cfg.public_key | ||
| if lf_cfg.secret_key: | ||
| kwargs["secret_key"] = lf_cfg.secret_key | ||
| if lf_cfg.host: | ||
| kwargs["host"] = lf_cfg.host | ||
| LangfuseClient(**kwargs) | ||
| logger.info("Langfuse initialized with explicit credentials from config") | ||
| LangfuseAsyncOpenAI = getattr(import_module("langfuse.openai"), "AsyncOpenAI") | ||
| cls._patch_langfuse_stream_close() | ||
| logger.info("Creating Langfuse AsyncOpenAI client (langfuse_enabled=True)") | ||
| return LangfuseAsyncOpenAI(**client_kwargs) | ||
| except ImportError: | ||
| logger.warning( | ||
| "Langfuse is enabled but 'langfuse' package is not available. " | ||
| "Falling back to standard AsyncOpenAI client." | ||
| ) | ||
|
|
Member
There was a problem hiding this comment.
Что-то не очень здоровое.
- Валидацию можно вынести в модельку
- Зачем-то собираются лишние kwargs с лишними if
- Если юзер не заимпортил модуль, лучше явно упасть чем неявно фолбекнуться
- Какую проблему решает патч stream close?
прогонял на этом тесте, вроде всё работает
from sgr_agent_core.agent_config import GlobalConfig
config = GlobalConfig().from_yaml("config.yaml")
from langfuse import Langfuse
Langfuse(
public_key=config.langfuse.public_key,
secret_key=config.langfuse.secret_key,
host=config.langfuse.host,
)
from langfuse.openai import AsyncOpenAI
async_client = AsyncOpenAI(
base_url=config.llm.base_url,
api_key=config.llm.api_key,
)
completion = await async_client.chat.completions.create(
name="test-chat",
model="gpt-4o",
messages=[
{"role": "system", "content": "Tell me about dirigables"},
{"role": "user", "content": "Tell me about dirigables"}],
temperature=0,
metadata={"someMetadataKey": "someValue"},
stream=True
)
async for chunk in completion:
print(chunk.choices[0].delta.content, end="")
print(Langfuse)
print(completion)
Collaborator
Author
There was a problem hiding this comment.
- через kwargs собирается, потому что Langfuse с пустыми параметрами ( когда kwargs будут пустые) инициализируется с env переменными LANGFUSE_SECRET_KEY ,
LANGFUSE_PUBLIC_KEY ,
LANGFUSE_BASE_URL .
Member
There was a problem hiding this comment.
- У нас уже есть готовая pydantic моделька, которая в себе это хранит, валидирует и всё такое. Зачем возвращаться обратно к raw словарю?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Changes
Configuration: Added
langfuseflag toAgentConfigfor enabling Langfuse tracinglangfuse: true/false) or environment variable (SGR__LANGFUSE)falseAgent Factory: Updated
_create_client()to support Langfuse AsyncOpenAI clientlangfuse.openai.AsyncOpenAIwhen enabledopenai.AsyncOpenAIif Langfuse package unavailable_patch_langfuse_stream_close()to fix streaming compatibility issuesDependencies: Added
langfuse>=4.0.0to project dependenciesDocumentation: Added Langfuse configuration guide in English and Russian
Tests: Added comprehensive test coverage